package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Fruit;

import java.io.*;
import java.util.ArrayList;

public class OtherFruitDao implements BaseFruitDao1{
    private static ArrayList<Fruit> fruits = new ArrayList<>();

    static {
        try {
            BufferedReader br = new BufferedReader(new FileReader("FruitMarket\\fruits.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] split = line.split(System.lineSeparator());
                for (int i = 0; i < split.length; i++) {
                    String[] strings = split[i].split(",");
                    Fruit fruit = new Fruit(strings[0], strings[1], Integer.parseInt(strings[2]), Integer.parseInt(strings[3]));
                    fruits.add(fruit);
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 查看所有水果对象并返回
    public Fruit[] findAllFruit() {
        reSave();
        Fruit[]  f= new Fruit[fruits.size()];

        for (int i = 0; i < f.length; i++) {
            f[i] = fruits.get(i);
        }
        return f;
    }

    // 添加
    public boolean addFruit(Fruit f) {
        // 调用集合中的add()方法来实现添加功能
        fruits.add(f);
        reSave();
        return true;
    }

    // 删除
    public void deleteFruit(String deleteId) {
        int index = getIndex(deleteId);
        // 调用集合中的remove()方法来实现删除功能
        fruits.remove(index);
        reSave();
    }

    public int getIndex(String deleteId) {
        int index = -1;
        for (int i = 0; i < fruits.size(); i++) {
            Fruit fruit = fruits.get(i);
            if (fruit != null && fruit.getId().equals(deleteId)) {
                index = i;
                break;
            }
        }
        return index;
    }

    //修改
    public void updateFruit(String updateId, Fruit newFruit) {
        // 查找updateId在容器中的索引位置
        int index = getIndex(updateId);
        // 索引位置的数据替换成新的数据
        fruits.set(index, newFruit);
        reSave();
    }

    private void reSave() {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("FruitMarket\\fruits.txt"));
            for (int i = 0; i < fruits.size(); i++) {
                bw.write(fruits.get(i) + "");
                bw.write(System.lineSeparator());
                bw.flush();
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
